import time

import numpy as np


def compare_lists_and_arrays():
  my_list = [1, 2, 3]
  print(my_list[0])

  my_array = np.array([1, 2, 3])
  print(my_array[0])

  my_list[0] = -1
  my_array[0] = -1
  print(my_list)
  print(my_array)

def compare_speed():
  t0 = time.time()
  # python list
  # 创建一个包含0到99的列表
  l = list(range(100))
  # 执行10000次循环
  for _ in range(10000):
    # 遍历列表中的每个元素
    for i in range(len(l)):
      # 将每个元素的值加1
      l[i] += 1
  print(l)

  t1 = time.time()
  # numpy array
  a = np.array(l)
  for _ in range(10000):
    # 对numpy数组进行加1操作会广播到每个元素
    # 这是numpy的广播(Broadcasting)特性
    # numpy会对数组中的每个元素执行相同的操作
    a += 1
  print(a)

  print("Python list spend {:.3f}s".format(t1 - t0))
  print("Numpy array spend {:.3f}s".format(time.time() - t1))

if __name__ == "__main__":
  compare_speed()
